import { CLOUD_CONFIG } from '../../cloud-config.js'

export default class SimpleCloudManager {
  constructor() {
    this.roomId = null
    this.playerId = null
    this.isCreator = false
    this.gameStarted = false
    this.openid = null
    this.db = null
    this.watcher = null
    
    // 回调函数
    this.onRoomCreated = null
    this.onRoomJoined = null
    this.onGameStart = null
    this.onMoveReceived = null
    this.onGameOver = null
    this.onOpponentConnected = null
    this.onOpponentDisconnected = null
    
    this.initCloud()
  }

  // 初始化云开发
  initCloud() {
    try {
      if (typeof wx !== 'undefined' && wx.cloud) {
        console.log('正在初始化云开发，环境ID:', CLOUD_CONFIG.envId)
        
        wx.cloud.init({
          env: CLOUD_CONFIG.envId,
          traceUser: true
        })
        
        this.db = wx.cloud.database()
        console.log('云开发初始化成功')
      } else {
        console.warn('云开发不可用')
        throw new Error('云开发不可用')
      }
    } catch (error) {
      console.error('云开发初始化失败:', error)
      throw error
    }
  }

  // 生成房间ID
  generateRoomId() {
    return Math.random().toString(36).substr(2, 6).toUpperCase()
  }

  // 获取用户openid
  async getOpenid() {
    if (!this.openid) {
      try {
        console.log('获取OpenID...')
        const { result } = await wx.cloud.callFunction({
          name: 'getOpenId'
        })
        console.log('OpenID获取结果:', result)
        
        if (result && result.openid) {
          this.openid = result.openid
        } else {
          console.warn('OpenID获取失败，使用随机ID')
          this.openid = 'user_' + Math.random().toString(36).substr(2, 9)
        }
      } catch (error) {
        console.error('获取openid失败:', error)
        
        // 检查是否是部署问题
        if (error.errMsg && error.errMsg.includes('function not found')) {
          console.error('getOpenId 云函数未部署')
        }
        
        // 使用随机ID作为备选
        this.openid = 'user_' + Math.random().toString(36).substr(2, 9)
      }
    }
    return this.openid
  }

  // 调用云函数
  async callCloudFunction(type, data = {}) {
    try {
      // 只在非轮询调用时输出详细日志
      if (type !== 'get_room_info') {
        console.log(`调用云函数 roomManager，类型: ${type}，数据:`, data)
      }
      
      const { result } = await wx.cloud.callFunction({
        name: 'roomManager',
        data: {
          type: type,
          openid: this.openid,
          ...data
        }
      })
      
      // 只在非轮询调用时输出详细日志
      if (type !== 'get_room_info') {
        console.log('云函数返回结果:', result)
      }
      
      // 检查返回结果
      if (!result) {
        console.error('云函数返回空结果')
        return {
          success: false,
          message: '云函数返回空结果'
        }
      }
      
      return result
    } catch (error) {
      console.error('调用云函数失败:', error)
      
      // 检查是否是部署问题
      if (error.errMsg && error.errMsg.includes('function not found')) {
        return {
          success: false,
          message: '云函数未部署，请先部署 roomManager 云函数'
        }
      }
      
      return {
        success: false,
        message: '网络错误: ' + (error.errMsg || error.message || '未知错误')
      }
    }
  }

  // 创建房间
  async createRoom() {
    try {
      console.log('创建房间...')
      
      const openid = await this.getOpenid()
      const roomId = this.generateRoomId()
      
      console.log('创建房间参数:', { openid, roomId })
      
      // 调用云函数创建房间
      const result = await this.callCloudFunction('create_room', {
        roomId: roomId,
        playerName: '玩家1'
      })
      
      if (result.success) {
        this.roomId = roomId
        this.playerId = openid
        this.isCreator = true
        this.gameStarted = false
        
        console.log('房间创建成功:', roomId)
        
        // 开始监听房间状态变化
        this.startWatching()
        
        if (this.onRoomCreated) {
          this.onRoomCreated(roomId, true)
        }
        
        // 为创建者添加更频繁的检查，确保能检测到游戏开始
        console.log('创建者：启动游戏开始检测')
        this.startGameStartDetection()
        
        return roomId
      } else {
        throw new Error(result.message)
      }
    } catch (error) {
      console.error('创建房间失败:', error)
      throw error
    }
  }

  // 加入房间
  async joinRoom(roomId) {
    try {
      console.log('加入房间:', roomId)
      
      const openid = await this.getOpenid()
      
      // 调用云函数加入房间
      const result = await this.callCloudFunction('join_room', {
        roomId: roomId,
        playerName: '玩家2'
      })
      
      if (result.success) {
        this.roomId = roomId
        this.playerId = openid
        this.isCreator = false
        this.gameStarted = false
        
        console.log('房间加入成功:', roomId)
        
        // 开始监听房间状态变化
        this.startWatching()
        
        if (this.onRoomJoined) {
          this.onRoomJoined(roomId, false)
        }
        
        // 延迟检查游戏状态，确保游戏开始
        setTimeout(() => {
          this.checkGameStartStatus()
        }, 1000)
        
        return roomId
      } else {
        throw new Error(result.message)
      }
    } catch (error) {
      console.error('加入房间失败:', error)
      throw error
    }
  }

  // 开始监听房间状态变化
  startWatching() {
    if (!this.roomId || !this.db) return
    
    try {
      console.log('开始监听房间状态变化:', this.roomId)
      
      // 停止之前的监听
      this.stopWatching()
      
      // 由于 watch 机制可能有问题，直接使用轮询模式
      console.log('使用轮询模式监听房间状态')
      this.fallbackToPolling()
      
      // 注释掉 watch 机制，直接使用轮询
      /*
      // 使用 watch 方法监听房间数据变化
      this.watcher = this.db.collection('rooms').doc(this.roomId).watch({
        onChange: snapshot => {
          console.log('房间数据变化:', snapshot)
          
          if (snapshot.docs && snapshot.docs.length > 0) {
            const roomData = snapshot.docs[0]
            this.handleRoomUpdate(roomData)
          }
        },
        onError: err => {
          console.error('监听房间状态失败:', err)
          // 监听失败时，回退到轮询模式
          this.fallbackToPolling()
        }
      })
      
      console.log('房间监听启动成功')
      */
    } catch (error) {
      console.error('启动房间监听失败:', error)
      // 监听启动失败时，回退到轮询模式
      this.fallbackToPolling()
    }
  }

  // 停止监听
  stopWatching() {
    if (this.watcher) {
      this.watcher.close()
      this.watcher = null
      console.log('停止房间监听')
    }
  }

  // 回退到轮询模式
  fallbackToPolling() {
    console.log('回退到轮询模式')
    if (this.pollingTimer) {
      clearInterval(this.pollingTimer)
    }
    
    this.pollingTimer = setInterval(() => {
      this.pollRoomStatus()
    }, 3000)
  }

  // 停止轮询
  stopPolling() {
    if (this.pollingTimer) {
      clearInterval(this.pollingTimer)
      this.pollingTimer = null
    }
  }

  // 轮询房间状态（作为备用方案）
  async pollRoomStatus() {
    if (!this.roomId) return
    
    try {
      const result = await this.callCloudFunction('get_room_info', {
        roomId: this.roomId
      })
      
      if (result.success) {
        const roomData = result.data
        this.handleRoomUpdate(roomData)
      }
    } catch (error) {
      console.error('轮询房间状态失败:', error)
    }
  }

  // 检查游戏开始状态
  async checkGameStartStatus() {
    if (!this.roomId) return
    
    try {
      console.log('检查游戏开始状态...')
      const result = await this.callCloudFunction('get_room_info', {
        roomId: this.roomId
      })
      
      if (result.success) {
        const roomData = result.data
        console.log('当前房间状态:', roomData)
        
        // 如果房间状态是playing但游戏还没开始，强制触发游戏开始
        if (roomData.status === 'playing' && !this.gameStarted) {
          console.log('强制触发游戏开始')
          this.handleRoomUpdate(roomData)
        }
      }
    } catch (error) {
      console.error('检查游戏开始状态失败:', error)
    }
  }

  // 启动游戏开始检测（为创建者专用）
  startGameStartDetection() {
    if (this.gameStartDetectionTimer) {
      clearInterval(this.gameStartDetectionTimer)
    }
    
    // 创建者需要更频繁地检查，因为可能watch机制有问题
    this.gameStartDetectionTimer = setInterval(() => {
      if (this.isCreator && !this.gameStarted) {
        console.log('创建者：定期检查游戏开始状态')
        this.checkGameStartStatus()
      } else if (this.gameStarted) {
        // 游戏已开始，停止检测
        this.stopGameStartDetection()
      }
    }, 2000) // 每2秒检查一次
  }

  // 停止游戏开始检测
  stopGameStartDetection() {
    if (this.gameStartDetectionTimer) {
      clearInterval(this.gameStartDetectionTimer)
      this.gameStartDetectionTimer = null
      console.log('停止游戏开始检测')
    }
  }

  // 处理房间更新
  handleRoomUpdate(roomData) {
    console.log('处理房间更新:', {
      status: roomData.status,
      gameStarted: this.gameStarted,
      player1: roomData.player1,
      player2: roomData.player2,
      currentPlayer: roomData.currentPlayer,
      isCreator: this.isCreator,
      hasChessboard: !!roomData.chessboard
    })
    
    // 检查游戏是否开始
    if (roomData.status === 'playing' && !this.gameStarted) {
      console.log('游戏开始条件满足，触发游戏开始')
      this.gameStarted = true
      
      // 停止游戏开始检测
      this.stopGameStartDetection()
      
      if (this.onGameStart) {
        console.log('调用游戏开始回调')
        this.onGameStart()
      } else {
        console.warn('游戏开始回调未设置')
      }
      
      if (this.onOpponentConnected) {
        console.log('调用对手连接回调')
        this.onOpponentConnected()
      }
    }
    
    // 处理落子同步
    if (roomData.status === 'playing' && this.gameStarted && roomData.chessboard) {
      console.log('检测到棋盘更新，同步落子信息')
      
      // 检查是否是当前玩家的回合 - 确保类型一致
      const currentPlayerOpenid = String(roomData.currentPlayer)
      const myPlayerOpenid = String(this.playerId)
      const isMyTurn = currentPlayerOpenid === myPlayerOpenid
      
      console.log('当前回合检查:', {
        currentPlayer: currentPlayerOpenid,
        myPlayerId: myPlayerOpenid,
        isMyTurn: isMyTurn,
        gameStarted: this.gameStarted,
        hasChessboard: !!roomData.chessboard
      })
      
      // 更新棋盘状态 - 无论是否是我的回合都要更新棋盘
      if (this.onMoveReceived) {
        console.log('调用落子接收回调，更新棋盘')
        this.onMoveReceived(roomData.chessboard, currentPlayerOpenid)
      } else {
        console.warn('落子接收回调未设置')
      }
    }
    
    // 检查游戏是否结束
    if (roomData.status === 'finished' && roomData.winner !== null) {
      console.log('游戏结束:', roomData.winner)
      if (this.onGameOver) {
        this.onGameOver(roomData.winner)
      }
      
      // 游戏结束后停止监听
      this.stopWatching()
      this.stopGameStartDetection()
    }
    
    // 检查对手是否断开连接
    if (roomData.status === 'waiting' && this.gameStarted) {
      console.log('对手断开连接')
      this.gameStarted = false
      
      if (this.onOpponentDisconnected) {
        this.onOpponentDisconnected()
      }
    }
  }

  // 下棋（兼容旧版本）
  async makeMove(row, col, player) {
    if (!this.roomId) {
      throw new Error('未在房间中')
    }
    
    try {
      const result = await this.callCloudFunction('make_move', {
        roomId: this.roomId,
        row: row,
        col: col,
        player: player
      })
      
      if (result.success) {
        if (this.onMoveReceived) {
          this.onMoveReceived(result.data)
        }
        
        return result.data
      } else {
        throw new Error(result.message)
      }
    } catch (error) {
      console.error('下棋失败:', error)
      throw error
    }
  }

  // 实时落子同步（新版本）
  async placePiece(x, y) {
    if (!this.roomId) {
      throw new Error('未在房间中')
    }
    
    try {
      console.log(`玩家落子: (${x}, ${y})`)
      console.log('落子参数:', {
        roomId: this.roomId,
        x: x,
        y: y,
        playerId: this.playerId,
        isCreator: this.isCreator
      })
      
      const result = await this.callCloudFunction('place_piece', {
        roomId: this.roomId,
        x: x,
        y: y
      })
      
      console.log('落子云函数返回结果:', result)
      
      if (result.success) {
        console.log('落子成功:', result.message)
        
        if (result.data && result.data.isWin) {
          console.log('游戏结束，获胜者:', result.data.winner)
          if (this.onGameOver) {
            this.onGameOver(result.data.winner)
          }
        }
        
        return result.data
      } else {
        console.error('落子失败:', result.message)
        throw new Error(result.message)
      }
    } catch (error) {
      console.error('落子失败:', error)
      throw error
    }
  }

  // 离开房间
  async leaveRoom() {
    if (!this.roomId) return
    
    try {
      await this.callCloudFunction('leave_room', {
        roomId: this.roomId,
        playerName: this.isCreator ? '玩家1' : '玩家2'
      })
    } catch (error) {
      console.error('离开房间失败:', error)
    } finally {
      this.stopWatching()
      this.stopPolling()
      this.roomId = null
      this.playerId = null
      this.isCreator = false
      this.gameStarted = false
    }
  }

  // 获取分享链接
  getShareLink() {
    if (!this.roomId) return null
    
    return {
      title: '五子棋对战',
      path: `/pages/game/game?roomId=${this.roomId}`,
      imageUrl: '/images/share.jpg'
    }
  }

  // 清理资源
  cleanup() {
    console.log('清理云管理器资源')
    this.stopWatching()
    this.stopPolling()
    this.stopGameStartDetection()
    this.roomId = null
    this.playerId = null
    this.isCreator = false
    this.gameStarted = false
  }

  // 调试方法：手动检查游戏状态
  async debugCheckGameStatus() {
    if (!this.roomId) {
      console.log('调试：未在房间中')
      return
    }
    
    try {
      console.log('调试：手动检查游戏状态')
      const result = await this.callCloudFunction('get_room_info', {
        roomId: this.roomId
      })
      
      if (result.success) {
        const roomData = result.data
        console.log('调试：房间状态详情:', {
          roomId: roomData.roomId,
          status: roomData.status,
          player1: roomData.player1,
          player2: roomData.player2,
          currentPlayer: roomData.currentPlayer,
          gameStarted: this.gameStarted,
          isCreator: this.isCreator
        })
        
        // 如果状态是playing但游戏还没开始，强制触发
        if (roomData.status === 'playing' && !this.gameStarted) {
          console.log('调试：强制触发游戏开始')
          this.handleRoomUpdate(roomData)
        }
      }
    } catch (error) {
      console.error('调试：检查游戏状态失败:', error)
    }
  }
} 